# coding utf-8
#!/usr/bin/env python3
import requests
from requests_html import HTMLSession
import os
from downloader import DownImg

baseSavePath = './images/'
session = HTMLSession()

os.makedirs(baseSavePath, exist_ok=True)

Baseurl = 'https://alpha.wallhaven.cc/random?page='
# 定义初始页码
curPage = 1
maxPage=input('请输入下载的页数:')

def getImgPage(baseurl, pageIndex):
    response = session.get(baseurl+str(pageIndex))
    if response.status_code != 200:
        print("请求失败,返回代码{0}".format(response.status_code))
        print(response.html)
        getImgPage(baseurl, pageIndex)
        return
    imgPages = response.html.find('a.preview')
    # 总页码
    totalPage = response.html.find(
        'span.thumb-listing-page-num')[0].text.split('/')[1].strip()
    Page = response.html.find(
        'span.thumb-listing-page-num')[0].text.split('/')[0].strip()
    print("当前正在下载第%s页,一共有%s页数据" % (Page, totalPage))
    # 调用下载
    for imgPage in imgPages:
        DownImg(baseSavePath, imgPage.attrs['href'])

    # 下载完成
    if(totalPage == Page):
        print("下载完成")
        return
    # 下一页
    curPage = int(Page)+1
    if(int(maxPage)+1==int(curPage)):
        print('下载完成，以下载%d页的数据'%curPage)
        return
    getImgPage(baseurl, curPage)


if __name__ == '__main__':
    getImgPage(Baseurl, curPage)
